package org.exteen.exec;

import org.apache.commons.jexl2.Expression;
import org.exteen.output.ExteenStream;
import org.exteen.parser.EscapedString;
import org.exteen.parser.Node;

public class Tag {

    public void doTag(ExteenContext ctx, ExteenStream stream) {
        doBody(ctx, stream);
    }

    public void doBody(ExteenContext ctx, ExteenStream stream) {
        Node node = ctx.getNode();
        for (Object childNode: node.getChildren()) {
            if (childNode instanceof String || childNode instanceof EscapedString) {
                stream.printText(escape(childNode));
            } else if (childNode instanceof Expression) {
                Expression ex = (Expression) childNode;
                Object value = ex.evaluate(ctx);
                if (value != null) {
                    stream.printText(escape(value));
                }
            } else if (childNode instanceof Node) {
                Node c = (Node) childNode;
                Tag tag = ctx.getTagForNode(c);
                ExteenContext childContext = ctx.createChildContext(c);
                tag.doTag(childContext, stream);
                childContext.release();
            }
        }
    }

    protected String escape(Object obj) {
        if (obj instanceof EscapedString || obj instanceof Number) {
            return obj.toString();
        }
        // TODO - optimize
        return obj.toString().replaceAll("\"", "&quot;").replaceAll("<", "&lt;").replaceAll(">", "&gt;");
    }
}
